package com.iyue.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.google.gson.Gson;
import com.iyue.SpringHelper;
import com.iyue.activity.pojo.ActivityInfo;
import com.iyue.activity.pojo.ActivityPost;
import com.iyue.activity.pojo.UserPostLimit;
import com.iyue.activity.service.ActivityBiz;
import com.iyue.activity.service.PostBiz;
import com.iyue.framework.BaseAction;
import com.iyue.framework.cache.IMemcachedCache;
import com.iyue.framework.util.GsonUtil;
import com.iyue.servlet.taglibs.Functions;
import com.iyue.sys.pojo.SysAudit;
import com.iyue.sys.service.Audit;
import com.iyue.sys.service.Keyword;
import com.iyue.user.helper.UserFunctions;
import com.iyue.user.pojo.UserBasic;
import com.iyue.util.IpSafe;

/**
 * 《活动首页》实现类
 * 
 * @author 孙晓晔
 * @version $Id: Portal.java,v 1.2 2011/01/05 09:24:31 fresh Exp $
 */
public class Post extends Activity {

	private static final String USER_POST_LIMIT = "com.iyue.activity.pojo.post_limit_";
	/**
	 * 评论限制
	 */
	private static final Integer POST_LIMIT = 10;

	/*
	 * 网站首页
	 */
	public ActionForward layout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {

		return action.display(request, response, "layout");
	}

	/**
	 * 评论限制
	 */
	public ActionForward addPost(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		Boolean isajax = StringUtils.isNotEmpty(request.getParameter("ajax"));
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}

		String backurl = request.getParameter("go");
		if (StringUtils.isBlank(backurl)) {
			backurl = "/portal.do?do=Portal.layout";
		}

		String msg = "";
		String aid = request.getParameter("aid");
		if (StringUtils.isBlank(aid) || !StringUtils.isNumeric(aid)) {
			msg = "请选择需要评论的活动";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));

			return null;
		}

		Integer username = u(request);
		if (limit(username)) {
			msg = "你评论已经超出限制,明天再来吧!";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));
			return null;
		}

		if (check(request, "activity_post_" + username + "_" + aid, null)) {
			msg = "你评论的太快了，休息下!";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));
			return null;
		}

		String content = request.getParameter("content");
		if (StringUtils.isBlank(content)) {
			msg = "请输入评论内容!";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));

			return null;
		}

		Keyword key = (Keyword) SpringHelper.getBean("Keyword");
		if (key.isIllegal(content)) {
			msg = "您输入的评论内容中包含违规词,请重新输入!";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));

			return null;
		}

		ActivityBiz biz = (ActivityBiz) SpringHelper.getBean("ActivityBiz");
		ActivityInfo info = biz.getActivityInfo(new Integer(aid));
		if (info == null) {
			msg = "该活动不存在!";
			Redirect(request, response, backurl + "&msg="
					+ Functions.encode(msg));

			return null;
		}

		UserBasic basic = UserFunctions.user(username.toString());
		ActivityPost post = new ActivityPost();
		post.setUsername(username);
		post.setNickname(basic.getNickname());
		post.setAid(new Integer(aid));
		post.setContent(content);
		post.setIpaddr(IpSafe.getIp(request));

		Audit audit = (Audit) SpringHelper.getBean("Audit");
		boolean ss = audit.audit(SysAudit.PRODUCT_ACTIVITY_POST);
		if (ss) {
			post.setAudit(SysAudit.AUDIT_DEFAULT);
		} else {
			post.setAudit(SysAudit.AUDIT_OK);
		}

		Date now = new Date();
		post.setCreatetime(now);
		PostBiz post_biz = (PostBiz) SpringHelper.getBean("PostBiz");
		int ret = post_biz.save_post(post);
		if (ret > 0) {
			addCount(username, 1);
			msg = "操作成功";
		} else {
			msg = "操作失败";
		}
		if (isajax) {
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.getWriter().write(msg);
			return null;
		}
		Redirect(request, response, backurl + "&msg=" + Functions.encode(msg));

		return null;
	}
	public ActionForward addPost2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}
		String msg = "";
		String aid = request.getParameter("aid");
		if (StringUtils.isBlank(aid) || !StringUtils.isNumeric(aid)) {
			msg = "请选择需要评论的活动";
			response.getWriter().write(msg);
			return null;
		}

		Integer username = u(request);
		if (limit(username)) {
			msg = "你评论已经超出限制,明天再来吧!";
			response.getWriter().write(msg);
			return null;
		}

		if (check(request, "activity_post_" + username + "_" + aid, null)) {
			msg = "你评论的太快了，休息下!";
			response.getWriter().write(msg);
			return null;
		}

		String content = request.getParameter("content");
		if (StringUtils.isBlank(content)) {
			msg = "请输入评论内容!";
			response.getWriter().write(msg);
			return null;
		}

		Keyword key = (Keyword) SpringHelper.getBean("Keyword");
		if (key.isIllegal(content)) {
			msg = "您输入的评论内容中包含违规词,请重新输入!";
			response.getWriter().write(msg);
			return null;
		}

		ActivityBiz biz = (ActivityBiz) SpringHelper.getBean("ActivityBiz");
		ActivityInfo info = biz.getActivityInfo(new Integer(aid));
		if (info == null) {
			msg = "该活动不存在!";
			response.getWriter().write(msg);
			return null;
		}

		UserBasic basic = UserFunctions.user(username.toString());
		ActivityPost post = new ActivityPost();
		post.setUsername(username);
		post.setNickname(basic.getNickname());
		post.setAid(new Integer(aid));
		post.setContent(content);
		post.setIpaddr(IpSafe.getIp(request));

		Audit audit = (Audit) SpringHelper.getBean("Audit");
		boolean ss = audit.audit(SysAudit.PRODUCT_ACTIVITY_POST);
		if (ss) {
			post.setAudit(SysAudit.AUDIT_DEFAULT);
		} else {
			post.setAudit(SysAudit.AUDIT_OK);
		}

		Date now = new Date();
		post.setCreatetime(now);
		PostBiz post_biz = (PostBiz) SpringHelper.getBean("PostBiz");
		int ret = post_biz.save_post(post);
		if (ret > 0) {
			addCount(username, 1);
			msg = "操作成功";
		} else {
			msg = "操作失败";
		}
		
		response.getWriter().write(msg);		
		return null;
	}

	private boolean limit(Integer username) {
		if (username == null) {
			return true;
		}

		UserPostLimit ret = user_post_limit(username);
		if (ret == null) {
			return false;
		}

		Date now = new Date();
		Integer count = 0;
		Date createtime = ret.getCreatetime();
		String daytime = date(createtime, "yyyy-MM-dd");
		if (date(now, "yyyy-MM-dd").equals(daytime)) {
			count = ret.getCount();
		}

		if (count >= POST_LIMIT) {
			return true;
		}

		return false;
	}

	/**
	 * 
	 * @param username
	 * @param count
	 */
	private void addCount(Integer username, Integer count) {
		if (username == null || count == null || count == 0) {
			return;
		}

		UserPostLimit ret = user_post_limit(username);
		Date now = new Date();
		if (ret == null) {
			ret = new UserPostLimit();
			ret.setUsername(username);
			ret.setCount(count);
		} else {
			Date createtime = ret.getCreatetime();
			String daytime = date(createtime, "yyyy-MM-dd");
			if (date(now, "yyyy-MM-dd").equals(daytime)) {
				ret.incCount();
			} else {
				ret.setCount(count);
			}
		}

		ret.setCreatetime(now);

		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("ActivityIMemcachedCache");

		String key = USER_POST_LIMIT + username;

		Gson gson = GsonUtil.getGson();
		cache.add(key, gson.toJson(ret), IMemcachedCache.MONTH);
		return;
	}

	public static String date(Date date, String format) {
		if (date == null) {
			return "";
		}

		SimpleDateFormat sdf = new SimpleDateFormat(format);

		return sdf.format(date.getTime()).trim();
	}

	/**
	 * 每天限制用户评论10次
	 * 
	 * @param username
	 * @return
	 */
	private UserPostLimit user_post_limit(Integer username) {
		if (username == null) {
			return null;
		}

		Gson gson = GsonUtil.getGson();
		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("ActivityIMemcachedCache");
		String key = USER_POST_LIMIT + username;
		Object obj = cache.get(key);
		if (obj != null) {
			if (obj instanceof String) {
				String json = (String) obj;
				return gson.fromJson(json, UserPostLimit.class);
			} else {
				cache.delete(key);
			}
		}

		return null;
	}
}
